import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import { Row, Col, Card, Form, Input, Button, Modal, Divider, InputNumber, Checkbox, Tag,Radio } from 'antd';
import TableList from '@/components/TableList';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import styles from '../search.less';
import { nameMinLength, nameMaxLength, remarkMaxLength } from '@/utils/rule';

const { TextArea } = Input;
const FormItem = Form.Item;
const formLayout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 20 },
};

const CreateForm = Form.create()(props => {
  const {
    modalVisible,
    form,
    addDataFn,
    updateFn,
    handleModalVisible,
    text,
    form: { getFieldValue },
    loadingupdate,
    loadingadd,  
  } = props;
  const pwdMinLength = (rule, val, callback) => {
    if (!val) {
      callback();
    }
    if (val > getFieldValue('maxLength') || (val > getFieldValue('maxLength') && val > 64)) {
      callback('应小于最大长度');
    }
    if (val < getFieldValue('maxLength') && (val < 3 || val > 64)) {
      callback('长度范围为3-64');
    }
    callback();
  };

  const pwdMaxLength = (rule, val, callback) => {
    if (!val) {
      callback();
    }
    if (val < getFieldValue('minLength') || (val < getFieldValue('minLength') && val < 3)) {
      callback('应大于最小长度');
    }
    if (val > getFieldValue('minLength') && (val < 3 || val > 64)) {
      callback('长度范围为3-64');
    }

    callback();
  };

  const okHandle = () => {
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      if (text) {        
        updateFn(fieldsValue, text);        
      } else {
        addDataFn(fieldsValue);
      }
    });
  };
  

  return (
    <Modal
      destroyOnClose
      width={640}
      title={text ? '编辑密钥规则' : '新增密钥规则'}
      visible={modalVisible}
      onOk={okHandle}
      confirmLoading={loadingupdate || loadingadd}
      onCancel={() => handleModalVisible()}
      maskClosable={false}
    >
      <Row gutter={16}>
        <Col md={24}>
          <FormItem {...formLayout} label="规则名称">
            {form.getFieldDecorator('ruleName', {
              rules: [
                { required: true, whitespace: true, message: '规则名称不能为空' },                
                { min: nameMinLength()[0], message: nameMinLength()[1] },
                { max: nameMaxLength()[0], message: nameMaxLength()[1] },               
              ],
              initialValue: (text && text.ruleName) || '',
            })(<Input placeholder="请输入" />)}
          </FormItem>
        </Col>

        <Col md={24}>
          <FormItem {...formLayout} label="算法">
          {form.getFieldDecorator('algorithm', {
            rules: [{ required: true,}],
            initialValue: text&&text.algorithm || 'sm4'
          })(
          <Radio.Group>
            <Radio value="sm4">SM4</Radio>
            <Radio value="aes">AES</Radio>
            <Radio value="des3">DES3</Radio> 
            {/* <Radio value="rsa">RSA</Radio>
            <Radio value="sm2">SM2</Radio> */}
          </Radio.Group>
            )}
          </FormItem>
        </Col> 

        <Col md={24}>
          <FormItem {...formLayout} label="密钥长度">
            {form.getFieldDecorator('fixedLength', {
              rules: [{ required: true,}],
              initialValue: `${getFieldValue('algorithm') == 'des3' ? '32':'16'}`,
            })(
              <Input disabled />
            )}
          </FormItem>
        </Col>


        {/* <Col md={24}>
          <FormItem {...formLayout} label="密钥长度">
            {form.getFieldDecorator('length', {
              rules: [{ required: true, message: '请选择' }],
              initialValue: (text && (text.fixedLength? '0':'1')) || '0',
            })(
              <Radio.Group>
                <Radio value="0">固定长度</Radio>
                <Radio value="1">范围</Radio>
              </Radio.Group>
            )}
          </FormItem>
        </Col> */}

        {/* {getFieldValue('length') == '0' ? (
          <Fragment>
            <Col md={24} style={{display:'none'}}>
              <Form layout="inline">
                <FormItem labelCol={{ span: 12 }} wrapperCol={{ span: 12 }} label="长度范围">
                  {form.getFieldDecorator('minLength', {                  
                    initialValue: '',
                  })(<InputNumber min={3} max={64} style={{ width: 120 }} />)}
                </FormItem>
                <FormItem style={{ width: '30px', textAlign: 'right' }}>-</FormItem>
                <FormItem>
                  {form.getFieldDecorator('maxLength', {                 
                    initialValue: '',
                  })(<InputNumber min={3} max={64} style={{ width: 120 }} />)}
                </FormItem>
              </Form>
          </Col>
          <Col md={24}>           
          <FormItem {...formLayout} label="固定值">
            {form.getFieldDecorator('fixedLength', {                  
              rules: [
                { required: true, message: '密钥长度不能为空' }],              
              initialValue: (text && text.fixedLength) || 16,
            })(<InputNumber min={3} max={64} />)}
             <span className="ant-form-text" style={{color:'#999'}}>&nbsp;&nbsp;数值范围：3-64</span>
          </FormItem>
      </Col>
    </Fragment>
        ):(
          <Fragment>
          <Col md={24}>
          <Form layout="inline">
            <FormItem labelCol={{ span: 12 }} wrapperCol={{ span: 12 }} label="长度范围">
              {form.getFieldDecorator('minLength', {
                rules: [
                  { required: true, message: '长度不能为空' },
                  { validator: pwdMinLength },                 
                ],
                initialValue: (text && text.minLength) || 10,
              })(<InputNumber min={1} max={64} style={{ width: 120 }} />)}
            </FormItem>
            <FormItem style={{ width: '30px', textAlign: 'right' }}>-</FormItem>
            <FormItem>
              {form.getFieldDecorator('maxLength', {
                rules: [
                  { required: true, message: '长度不能为空' },
                  { validator: pwdMaxLength },                 
                ],
                initialValue: (text && text.maxLength) || 20,
              })(<InputNumber min={1} max={64} style={{ width: 120 }} />)}
            </FormItem>
          </Form>
      </Col>
      <Col md={24} style={{display:'none'}}>           
      <FormItem {...formLayout} label="固定值">
        {form.getFieldDecorator('fixedLength', { 
          initialValue: '',
        })(<InputNumber min={1} max={64} />)}
      </FormItem>
  </Col>
  </Fragment>
        )}   */}
     

     
        <Col md={24}>
          <FormItem {...formLayout} label="字符构成">
            {form.getFieldDecorator('character', {
              rules: [{ required: true, message: '请选择' }],
              initialValue: (text && [`${text.hasLetter==0?0:''}`,`${text.hasNumber==0?1:''}`,`${text.hasCharacter==0?2:''}`]) || ['0','1'],
            })(
              <Checkbox.Group>
                <Checkbox value="0">字母</Checkbox>
                <Checkbox value="1">数字</Checkbox>
                <Checkbox value="2">特殊字符</Checkbox>
              </Checkbox.Group>
            )}
             <span className="ant-form-text">（~!@#$%^&*()）</span>
          </FormItem>
        </Col>        

        <Col md={24}>
          <FormItem {...formLayout} label="描述">
            {form.getFieldDecorator('remark', {
              rules: [{ max: remarkMaxLength()[0], message: remarkMaxLength()[1] }],
              initialValue: text && text.remark || '',
            })(<TextArea style={{ minHeight: 32 }} rows={2} />)}
          </FormItem>
        </Col>
      </Row>
    </Modal>
  );
});
@Form.create()
/* eslint react/no-multi-comp:0 */
@connect(
  ({ pwdRule, loading }) => ({
    pwdRule,
    loading: loading.models.pwdRule,
    loadingadd: loading.effects['pwdRule/add'],
    loadingupdate: loading.effects['pwdRule/update'],
  }),
  dispatch => ({
    getPwdRulePageList: e => dispatch({ type: 'pwdRule/getPwdRulePageList', payload: e }),
    updatePwdRuleIsDefault: e =>
      dispatch({ type: 'pwdRule/updatePwdRuleIsDefault', payload: e }),
    dispatch,
  })
)
class pwdRule extends PureComponent {
  state = {
    modalVisible: false,    
    selectedRows: [],
    formValues: {},
    text: {}, 
  };

  columns = [
    {
      title: '密钥规则名称',
      dataIndex: 'ruleName',
      key: 'ruleName',
    },
    {
      title: '密钥长度',
      dataIndex: 'fixedLength',
      // render: text => (
      //   <Fragment>
      //     {text.fixedLength == null ? 
      //     <Fragment>{text.minLength} ~ {text.maxLength}</Fragment>:
      //     <Fragment>{text.fixedLength}</Fragment> 
      //   }
      //   </Fragment>),
     },      
    {
      title: '字符构成',
      render: text => (
        <Fragment>
          <span style={{ display: text.hasNumber == 0 ? '' : 'none' }}>&nbsp;数字&nbsp;</span>
          <span style={{ display: text.hasLetter == 0 ? '' : 'none' }}>&nbsp;字母&nbsp;</span>           
          <span style={{ display: text.hasCharacter == 0 ? '' : 'none' }}>&nbsp;特殊字符&nbsp;</span>
        </Fragment>
      ),     
    },    
    {
      title: '算法',
      dataIndex: 'algorithm',      
    },
    
    {
      title: '状态',
      dataIndex: 'statusFlag',   
      render: text => (
        <Fragment>
          {text == 1 ?<Tag color="green">在用</Tag>:<Tag color="red">未用</Tag>}
        </Fragment>
      ), 
    },
    {
      title: '备注',
      dataIndex: 'remark',    
      ellipsis:true,  
    },
    
    {
      title: '操作',
      width:110,
      render: (text) => (
        <Fragment>         
          {text.statusFlag == 0 ? (
            <Fragment>
              <a onClick={() => this.handleModalVisible(true, text)}>编辑</a>          
              <Divider type="vertical" />
              <a onClick={() => this.deleteData(text.keyRuleId)}>删除</a>            
            </Fragment>
          ) : null}
        </Fragment>
      ),
    },
  ];

  deleteData = id => {
    Modal.confirm({
      title: '删除',
      content: '您确认要删除选择的数据吗？',
      okText: '确认',
      cancelText: '取消',
      onOk: () => this.handleThisRowDelete(id),
    });
  };

  batchDelete = rows => {
    this.deleteData(rows); //批量删除
  };
  handleThisRowDelete = id => {
    const { dispatch } = this.props;
    return dispatch({
      type: 'pwdRule/deletePwdRule',
      payload: { keyRuleIds: id },
      callback: res => {
        if (res.result == 'ok') {
          Modal.success({ title: res.msg });
          this.pageList();
          this.setState({ selectedRows: [] });
        } else {
          Modal.error({ title: '操作失败', content: res.msg });
        }
      }, //callback
    });
  };

  componentDidMount() {
    this.props.getPwdRulePageList();
  }

  //复选框选择
  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };

  // 分页查询列表
  pageList(pageSize = 10, pageNum = 0) {
    const values = {
      ...this.state.formValues,
      pageSize: this.state.pagination ? this.state.pagination.pageSize : pageSize,
      pageNum: this.state.pagination ? this.state.pagination.current - 1 : pageNum,
    };
    this.props.getPwdRulePageList(values);
  }

  handleStandardTableChange(pagination) {
    this.setState({ pagination }, () => this.pageList());
  }

  //查询
  handleSearch = e => {
    e.preventDefault();
    const { form } = this.props;
    form.validateFields((err, fieldsValue) => {
      if (err) return;
      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };
      this.setState(
        {
          formValues: values,
          pagination: '',
        },
        () => this.pageList()
      );
    });
  };

  handleFormReset = () => {
    const { form } = this.props;
    form.resetFields();
  }; //重置
  renderSimpleForm() {
    const {
      form: { getFieldDecorator },
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={8} sm={24}>
            <FormItem label="密钥规则名称">
              {getFieldDecorator('ruleName')(<Input placeholder="请输入" />)}
            </FormItem>
          </Col>
          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
              <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
                重置
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  // 新增弹框的显示和隐藏
  handleModalVisible = (flag, text) => {
    this.setState({
      modalVisible: !!flag,
      text: text,
    });
  };

  // 更新接口
  updateFn = (fields, text) => {
    const { dispatch } = this.props;
    const params = {
      keyRuleId: text.keyRuleId,
      ruleName:fields.ruleName,
      minLength:fields.minLength,
      maxLength:fields.maxLength,
      fixedLength:fields.fixedLength,
      hasLetter:fields.character.includes('0')? 0:1,
      hasNumber:fields.character.includes('1')? 0:1,
      hasCharacter:fields.character.includes('2')? 0:1,
      algorithm:fields.algorithm,
      remark:fields.remark,
      statusFlag:fields.statusFlag,//0未使用，1在使用
    };    
    dispatch({
      type: 'pwdRule/update',
      payload: params,
      callback: res => {
        if (res.result == 'ok') {
          Modal.success({ title: res.msg });
          // form.resetFields();
          this.handleModalVisible();
          this.pageList();
        } else {
          Modal.error({ title: '操作失败', content: res.msg });
        }
      },
    });
  };

  // 增加接口
  addDataFn = fields => {
    const { dispatch } = this.props;   
    const params = {
      ruleName:fields.ruleName,
      minLength:fields.minLength,
      maxLength:fields.maxLength,     
      fixedLength:fields.fixedLength,
      hasLetter:fields.character.includes('0')? 0:1,
      hasNumber:fields.character.includes('1')? 0:1,
      hasCharacter:fields.character.includes('2')? 0:1,
      algorithm:fields.algorithm,
      remark:fields.remark,
      statusFlag:0,//0未使用，1在使用
    };
    dispatch({
      type: 'pwdRule/add',
      payload: params,
      callback: res => {
        if (res.result == 'ok') {
          Modal.success({ title: res.msg });
          this.pageList();
          // form.resetFields();
          this.handleModalVisible();
        } else {
          Modal.error({ title: '操作失败', content: res.msg });
        }
      },
    });
  };

  render() {
    const {
      pwdRule: { data },
      loading,
      loadingupdate,
      loadingadd,
    } = this.props;
    const { selectedRows, modalVisible, text, } = this.state;
    const parentMethods = {
      handleModalVisible: this.handleModalVisible,
      addDataFn: this.addDataFn,
      updateFn: this.updateFn,
    };   
    return (
      <PageHeaderWrapper title="密钥规则管理">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderForm()}</div>
            <div className={styles.tableListOperator}>
              <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
                新增
              </Button>
              {selectedRows.length > 0 && (
                <Button onClick={() => this.batchDelete(selectedRows)}>批量删除</Button>
              )}
            </div>
            <TableList
              size="middle"
              selectedRows={selectedRows}
              rowKey="keyRuleId"
              rowSelection={{
                selectedRowKeys: this.state.selectedRows,
                onChange: e => this.setState({ selectedRows: e }),
                getCheckboxProps: record => ({
                  disabled: record.statusFlag == 1,
                }),
              }}
              loading={loading}
              data={data}
              columns={this.columns}
              onChange={this.handleStandardTableChange.bind(this)}
            />
          </div>
          <CreateForm
            {...parentMethods}
            modalVisible={modalVisible}
            text={text}
            loadingupdate={loadingupdate}
            loadingadd={loadingadd}
          />      
        </Card>
      </PageHeaderWrapper>
    );
  }
}

export default pwdRule;
